<template>
  <div class="goods-comment">
    <div class="list mt-[40px]">
      <el-tree :data="list" :props="defaultProps" default-expand-all>
        <template v-slot="{ data }">
          <div class="item">
            <div class="user">
              <avatar>
                {{ data.publisher.slice(0, 1) }}
              </avatar>
              <p class="mt-[10px]">{{ data.publisher }}</p>
            </div>
            <div class="body">
              <div class="text" v-html="data.content" />
              <div class="time">
                <span>{{ data.createTime }}</span>
              </div>
            </div>
            <div class="operator">
              <el-button type="primary" link @click.stop="replay(data)"
                >回复</el-button
              >
              <el-button
                type="danger"
                link
                @click.stop="del(data)"
                v-if="useUserStoreHook().userId === data.publisherId"
                >删除</el-button
              >
            </div>
          </div>
        </template>
      </el-tree>
    </div>
    <div class="replay flex items-end mt-[50px]">
      <Editor v-model="content" />
      <el-button type="primary" @click="publishCon">发表</el-button>
    </div>
    <!-- 回复对话框 -->
    <el-dialog
      v-model="replayDialogVisible"
      title="回复"
      width="680"
      @closed="closed"
    >
      <Editor v-model="replayContent" />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="replayDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="replayConfim"> 回复 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { useUserStoreHook } from "@/store/modules/user";
import { getEvaluateList, publish, delEvaluate } from "@/api/shop";
import Editor from "@/components/Editor/index.vue";
import { onMounted } from "vue";
import { ref } from "vue";
import { useRoute } from "vue-router";
import type { EvaluateItem } from "@/api/shop/shop";
import { ElMessage, ElMessageBox } from "element-plus";
import avatar from "@/components/avatar/index.vue";
const route = useRoute();
onMounted(() => {
  getList();
});
const content = ref("");
// 获取评价列表
interface List extends EvaluateItem {
  children?: EvaluateItem[];
}
const list = ref<List[]>([]);
const getList = async () => {
  const res = await getEvaluateList({
    commodityId: Number(route.query.id)
  });
  list.value = generateTree(res.rows);
  console.log(list.value);
};
// 生成树结构
const generateTree = (data: EvaluateItem[]) => {
  // 创建一个字典，以id作为键，存储每个节点
  const nodesDict = {};

  // 遍历数据，将每个节点存储到字典中
  data.forEach(item => {
    nodesDict[item.id] = item;
  });

  // 创建根节点列表
  const rootNodes = [];

  // 遍历数据，将每个节点加入到其父节点的子节点列表中
  data.forEach(item => {
    const parentId = item.evaluateId;
    if (parentId === null) {
      // 没有父节点，说明是根节点
      rootNodes.push(item);
    } else {
      // 有父节点，将当前节点添加到父节点的子节点列表中
      const parentNode = nodesDict[parentId];
      if (parentNode) {
        if (!parentNode.children) {
          parentNode.children = [];
        }
        parentNode.children.push(item);
      }
    }
  });

  return rootNodes;
};
const defaultProps = {
  children: "children",
  label: "content"
};
// 发表
const publishCon = async () => {
  const res = await publish({
    commodityId: Number(route.query.id),
    content: content.value
  });
  if (res.code === 200) {
    ElMessage.success("评论成功");
    content.value = "";
    getList();
  }
};
// 回复评论
const replayDialogVisible = ref(false);
const evaluateId = ref<number>();
const replay = (item: EvaluateItem) => {
  replayDialogVisible.value = true;
  evaluateId.value = item.id;
};
const replayContent = ref("");
const replayConfim = async () => {
  const res = await publish({
    commodityId: Number(route.query.id),
    content: replayContent.value,
    evaluateId: evaluateId.value
  });
  if (res.code === 200) {
    ElMessage.success("回复成功");
    getList();
    replayDialogVisible.value = false;
  }
};
// 删除
const del = (item: EvaluateItem) => {
  ElMessageBox.confirm("您确定要删除吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    const res = await delEvaluate(item.id);
    if (res.code === 200) {
      ElMessage({
        type: "success",
        message: "删除成功"
      });
      getList();
    }
  });
};
const closed = () => {
  replayContent.value = "";
};
</script>
<style scoped lang="scss">
.goods-comment {
  .head {
    display: flex;
    padding: 30px 0;

    .data {
      display: flex;
      width: 340px;
      padding: 20px;

      p {
        flex: 1;
        text-align: center;

        span {
          display: block;

          &:first-child {
            font-size: 32px;
            color: $priceColor;
          }

          &:last-child {
            color: #999;
          }
        }
      }
    }

    .tags {
      display: flex;
      flex: 1;
      border-left: 1px solid #f5f5f5;

      .dt {
        width: 100px;
        font-weight: bold;
        line-height: 42px;
        text-align: right;
      }

      .dd {
        display: flex;
        flex: 1;
        flex-wrap: wrap;

        > a {
          width: 132px;
          height: 42px;
          margin-bottom: 20px;
          margin-left: 20px;
          line-height: 40px;
          color: #999;
          text-align: center;
          background: #f5f5f5;
          border: 1px solid #e4e4e4;
          border-radius: 4px;

          &:hover {
            color: $xtxColor;
            border-color: $xtxColor;
          }

          &.active {
            color: #fff;
            background: $xtxColor;
            border-color: $xtxColor;
          }
        }
      }
    }
  }

  .sort {
    height: 60px;
    margin: 0 20px;
    line-height: 60px;
    color: #666;
    border-top: 1px solid #f5f5f5;
    border-bottom: 1px solid #f5f5f5;

    > span {
      margin-left: 20px;
    }

    > a {
      margin-left: 30px;

      &.active,
      &:hover {
        color: $xtxColor;
      }
    }
  }

  .list {
    padding: 0 20px;

    .item {
      display: flex;
      width: 100%;
      padding: 25px 10px;
      border-bottom: 1px solid #f5f5f5;

      .user {
        flex-shrink: 0;
        width: 160px;

        img {
          width: 40px;
          height: 40px;
          overflow: hidden;
          border-radius: 50%;
        }

        span {
          padding-left: 10px;
          color: #666;
        }
      }

      .body {
        flex: 1;

        .score {
          line-height: 40px;

          .iconfont {
            padding-right: 3px;
            color: #ff9240;
          }

          .attr {
            padding-left: 10px;
            color: #666;
          }
        }
      }

      .el-button {
        flex-shrink: 0;
      }

      .text {
        margin-right: 20px;
        line-height: 24px;
        color: #666;
        white-space: normal;
      }

      .time {
        display: flex;
        justify-content: space-between;
        margin-top: 5px;
        color: #999;
      }
    }
  }

  :deep(.el-tree-node__content) {
    height: auto;
  }
}
</style>
